﻿namespace Mohe.Scada.WebApi.Common
{
    public static class ContextHelper
    {
        private static readonly AsyncLocal<Dictionary<string, object>> asyncLocal = new AsyncLocal<Dictionary<string, object>>();
        public static object GetItem(string key)
        {
            if (IocManager.Instance.Container != null)
            {
                IHttpContextAccessor service = IocManager.Instance.GetService<IHttpContextAccessor>();
                if (service == null)
                {
                    return string.Empty;
                }
                if (service.HttpContext != null && service.HttpContext.Items != null)
                {
                    service.HttpContext.Items.TryGetValue(key, out var value);
                    return value;
                }

                if (asyncLocal.Value != null)
                {
                    asyncLocal.Value.TryGetValue(key, out var value2);
                    return value2;
                }
            }

            return string.Empty;
        }

        public static void SetItem(string key, string value)
        {
            if (IocManager.Instance.Container == null)
            {
                return;
            }
            IHttpContextAccessor service = IocManager.Instance.GetService<IHttpContextAccessor>();
            if (service == null)
            {
                return;
            }
            if (service.HttpContext != null && service.HttpContext.Items != null)
            {
                if (service.HttpContext.Items.ContainsKey(key))
                {
                    service.HttpContext.Items.Remove(key);
                }

                service.HttpContext.Items.Add(key, value);
            }
            else if (asyncLocal.Value != null)
            {
                asyncLocal.Value.TryAdd(key, value);
            }
        }



        public static void RemoveItem(string key)
        {
            if (IocManager.Instance.Container == null)
            {
                return;
            }

            IHttpContextAccessor service = IocManager.Instance.GetService<IHttpContextAccessor>();
            if (service == null)
            {
                return;
            }
            if (service.HttpContext != null && service.HttpContext.Items != null)
            {
                if (service.HttpContext.Items.ContainsKey(key))
                {
                    service.HttpContext.Items.Remove(key);
                }
            }
            else if (asyncLocal.Value != null)
            {
                asyncLocal.Value.Remove(key);
            }
        }
    }
}
